package com.dream.cn.websocket.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket/{conId}")
@Service
public class WebSocketService {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String conId;

    @OnOpen
    public void onOpen(Session session,@PathParam("conId") String conId){
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        this.conId = conId;
        try {
            sendMessage("连接成功: "+ onlineCount);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        subOnlineCount();
    }

    /**
     *  收到用户端的消息
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session){
        for ( WebSocketService webSocketService :webSocketSet){
            try {
                webSocketService.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


    // 发送消息
    public  void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     *  发送会议消息消息
     * @param message
     * @param conId
     */
    public static void sendInfo(String message, @PathParam("conId") String conId) {
        for (WebSocketService webSocketService :webSocketSet ) {
            try{
                if (conId == null){
                    webSocketService.sendMessage(message);
                }else if(webSocketService.conId.equals(conId)){
                    webSocketService.sendMessage(message);
                }
            }catch (IOException e){
                continue;
            }

        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketService.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketService.onlineCount--;
    }

}
